package com.lxs.mall.exception;

import com.lxs.mall.common.ApiRestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 处理统一异常的handler
 *
 * @author 小松
 * @ControllerAdvice 用户拦截异常的
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception e) {
        log.error("Default Exception", e);
        return ApiRestResponse.error(LxsMallExceptionEnum.SYSTEM_ERROR);
    }

    /**
     * 业务异常 20000以后的
     */
    @ExceptionHandler(LxsMallException.class)
    @ResponseBody
    public Object handleLxsMallException(LxsMallException e) {
        log.error("LxsMallException", e);
        return ApiRestResponse.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiRestResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException:", e);
        return handleBindingResult(e.getBindingResult());
    }

    private ApiRestResponse handleBindingResult(BindingResult result) {
        //把异常处理成对外暴露的显示
        List<String> list = new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError objectError : allErrors) {
                String message = objectError.getDefaultMessage();
                list.add(message);
            }
        }
        if (list.size() == 0) {
            return ApiRestResponse.error(LxsMallExceptionEnum.REQUEST_PARAM_ERROR);
        }
        return ApiRestResponse.error(LxsMallExceptionEnum.REQUEST_PARAM_ERROR.getCode(), list.toString());
    }

    /**
     * 使用    @Validated注解出错的信息的整理
     * @param e
     * @return
     */
    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ApiRestResponse handle(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        StringBuilder stringBuilder = new StringBuilder();
        for (ConstraintViolation<?> validation : constraintViolations) {
            stringBuilder.append(validation.getMessage());
            break;
        }
        return ApiRestResponse
                .error(LxsMallExceptionEnum.REQUEST_PARAM_ERROR.getCode()
                        , stringBuilder.toString());
    }
}
